const connection = require("../../config/mysql.js");
const bcrypt = require("bcryptjs");
const fs = require("fs");
const path = require("path");

// 配置常量
const UPLOAD_DIR = path.join(__dirname, '../uploads');
const SUB_DIRECTORIES = ['pdf', 'tmp','img'];

// 读取SQL文件并准备表信息
function prepareTableList() {
    const sqlDir = path.join(__dirname, "./sql");
    return fs.readdirSync(sqlDir)
        .filter(file => file.endsWith('.sql'))
        .map(file => ({
            name: file.replace(".sql", ""),
            structure: fs.readFileSync(path.join(sqlDir, file), "utf-8")
        }));
}

// 检查并创建表
async function checkAndCreateTables() {
    const TableList = prepareTableList();
    const passTable = [];
    const newTable = [];

    try {
        for (const table of TableList) {
            const [result] = await connection.query(`SHOW TABLES LIKE '${table.name}'`);

            if (result.length === 0) {
                await connection.query(table.structure);
                console.log(`✅ Table ${table.name} created successfully`);
                newTable.push(table.name);
            } else {
                passTable.push(table.name);
            }
        }

        console.log('- 已存在的表:', passTable.join(', '));
        console.log('- 新创建的表:', newTable.join(', '));

        // 创建上传目录结构
        await createDirectoryStructure();
    } catch (err) {
        console.error('❌ Error during table setup:', err);
        throw err;
    }
}

// 创建目录结构
async function createDirectoryStructure() {
    try {
        if (!fs.existsSync(UPLOAD_DIR)) {
            fs.mkdirSync(UPLOAD_DIR);
            console.log('📁 Upload directory created');
        }

        for (const dir of SUB_DIRECTORIES) {
            const dirPath = path.join(UPLOAD_DIR, dir);
            if (!fs.existsSync(dirPath)) {
                fs.mkdirSync(dirPath);
                console.log(`📁 Subdirectory ${dir} created`);
            }
        }
    } catch (err) {
        console.error('❌ Error creating directories:', err);
        throw err;
    }
}

// 创建root用户
async function createRootUser() {
    try {
        const [rows] = await connection.execute("SELECT * FROM user WHERE username = ?", ["root"]);

        if (rows.length > 0) {
            return;
        }
        const password = await bcrypt.hash("123456", 10);
        const currentTime = new Date().toISOString().slice(0, 19).replace("T", " ");

        const sql = `
            INSERT INTO user (username, password, nick, type, headerUrl, creationTime)
            VALUES (?, ?, ?, ?, ?, ?)
        `;

        const values = [
            "root",
            password,
            "Root User",
            99,
            null,
            currentTime
        ];

        await connection.execute(sql, values);
        console.log('✅ Root user created successfully');
        console.log('   Username: root');
        console.log('   Password: 123456');
    } catch (err) {
        console.error('❌ Error creating root user:', err);
        throw err;
    }
}

// 主执行函数
async function main() {
    try {
        await checkAndCreateTables();
        await createRootUser();
    } catch (err) {
        console.error('❌ Initialization failed:', err);
        process.exit(1);
    }
}

// 执行主函数
main();